﻿using System;
using System.Xml.Linq;
using BattleFury.Lib.Extensions;
using BattleFury.Lib.Time;
using BattleFury.Time;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace BattleFury.Lib.Controls
{
	public class CelestialClock
		: Control
	{
		public static string PartBorder = "RadialClockBorder";
		public static string PartBackground = "RadialClockBackground";
		public static string PartCelestial = "RadialClockCelestial";

		private Part BorderPart { get; set; }
		private Part BackgroundPart { get; set; }
		private Part CelestialPart { get; set; }

		public WorldTime WorldTime { get; set; }
		public Color BorderColor { get; set; }

		public CelestialClock()
		{
			WorldTime = new BattleFuryWorldTime();
		}

		public override void Deserialize(XElement element, object callingObject)
		{
			base.Deserialize(element, callingObject);

			var month = element.GetInt("Month", 0);
			var day = element.GetInt("Day", 0);
			var year = element.GetInt("Year", 0);
			var hour = element.GetInt("Hour", 0);
			var minute = element.GetInt("Minute", 0);
			var width = element.GetInt("Width", 64);
			var height = element.GetInt("Height", 64);

			Size = new Vector2(width, height);

			BorderColor = element.GetColor("BorderColor", Color.White);

			WorldTime = new BattleFuryWorldTime(month, day, year, hour, minute);
		}

		public override void Update(GameTime gameTime)
		{
			WorldTime.Update(gameTime);

			if (BorderPart == null)
			{
				BorderPart = Skin[PartBorder];
				BackgroundPart = Skin[PartBackground];
				CelestialPart = Skin[PartCelestial];
			}
		}

		public override void Draw(GameTime gameTime)
		{
			var rotation = MathHelper.ToRadians(180 + ((float)(WorldTime.DayTick / 1438) * 360));
			
			SpriteBatch.Draw(Texture, Position + (Size / 2), BackgroundPart.SourceBounds, Color.White, rotation, (Size / 2), 1f, SpriteEffects.None, 1f);
			SpriteBatch.Draw(Texture, Position + (Size / 2), CelestialPart.SourceBounds, Color.White, rotation, (Size / 2), 1f, SpriteEffects.None, 1f);
			SpriteBatch.Draw(Texture, Position + (Size / 2), BorderPart.SourceBounds, BorderColor, 0f, (Size / 2), 1f, SpriteEffects.None, 1f);
		}
	}
}